package com.dcy.common.aspect;

import com.dcy.common.utils.UserInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author：dcy
 * @Description: 获取Header中的用户信息
 * @Date: 2021/5/8 14:21
 */
@Aspect
@Slf4j
@Component
@Order(-200)
public class BaseContextAspect {

    /**
     * 切入点
     */
    @Pointcut("execution(public * com.dcy.*.*.controller..*(..))")
    public void controllerMethod() {
    }

    /**
     * 前置通知
     *
     * @param joinPoint
     * @throws Exception
     * @since set手机端相关信息
     */
    @Before("controllerMethod()")
    public void logRequestInfo(JoinPoint joinPoint) throws Exception {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        // 设置用户信息
        UserInfoUtil.setUserInfo(request);
    }

    /**
     * 后置通知
     */
    @AfterReturning(returning = "rvt", pointcut = "controllerMethod()")
    public void logResultVoInfo(Object rvt) throws Exception {
        UserInfoUtil.clearUserInfo();
    }

    /**
     * 异常通知
     *
     * @param joinPoint
     * @param exception
     */
    @AfterThrowing(value = "controllerMethod()", throwing = "exception")
    public void doAfterThrowingAdvice(JoinPoint joinPoint, Throwable exception) {
        UserInfoUtil.clearUserInfo();
    }

}
